﻿using CommonType;
using MediatR;
using S_Userinfor.Domains;
using S_UserInfor.Infrasturctre.Interface;
using S_UserInfor.Read.Api.Application.Commands;

namespace S_UserInfor.Read.Api.Application.CommandsHanders
{
    public class UserCommandsHanders : IRequestHandler<UserCommands, PageResule<User>>
    {
        private readonly IDapperUserRepository _dapper;

        public UserCommandsHanders(IDapperUserRepository dapper)
        {
            _dapper = dapper;
        }
        async Task<PageResule<User>> IRequestHandler<UserCommands, PageResule<User>>.Handle(UserCommands request, CancellationToken cancellationToken)
        {
            var query = $" SELECT * FROM User WHERE 1=1";

            if (!string.IsNullOrEmpty(request.UName))
            {
                query += $" AND UName LIKE '%{request.UName}%'";
            }

            int tatalcount = query.Count();

            int pagecount = (int)Math.Ceiling((query.Count() * 1.0) / request.PageSize);

            query += $" LIMIT {(request.PageIndex - 1) * request.PageSize},@PageSize;";

            var List = await _dapper.SelectAsync(request.PageSize, query);

            return new PageResule<User>
            {
                TotalCount = tatalcount,
                PageCount = pagecount,
                Data = List,
            };
        }
    }
}
